const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const os = require('os');

// 创建日志输出通道
let outputChannel;

// 节流控制变量
let lastUpdateTime = 0;
const THROTTLE_INTERVAL = 200; // 200毫秒的节流间隔

// 获取状态文件路径
function getStateFilePath() {
    try {
        const homeDir = os.homedir();
        const statePath = path.join(homeDir, '.eclipse-cursor-sync-plugin', 'cursor_editor_state.json');
        
        // 验证路径是否合法
        if (!statePath || statePath.includes('..')) {
            throw new Error('Invalid state file path');
        }
        
        return statePath;
    } catch (error) {
        console.error('[Cursor Sync] Failed to get state file path:', error);
        return null;
    }
}

// 更新状态文件
function updateStateFile() {
    try {
        const now = Date.now();
        if (now - lastUpdateTime < THROTTLE_INTERVAL) {
            return; // 如果距离上次更新时间小于200毫秒，则跳过
        }
        
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            console.log('[Cursor Sync] No active editor');
            return;
        }
        
        const document = editor.document;
        if (!document) {
            console.log('[Cursor Sync] No active document');
            return;
        }
        
        const position = editor.selection.active;
        if (!position) {
            console.log('[Cursor Sync] No cursor position');
            return;
        }
        
        const state = {
            file_path: document.fileName,
            line_number: position.line + 1,  // 行号从1开始
            column: position.character + 1,
            timestamp: new Date().toISOString()
        };
        
        const statePath = getStateFilePath();
        if (!statePath) {
            console.error('[Cursor Sync] Invalid state path');
            return;
        }
        
        const stateDir = path.dirname(statePath);
        
        // 确保目录存在
        if (!fs.existsSync(stateDir)) {
            try {
                fs.mkdirSync(stateDir, { recursive: true });
            } catch (error) {
                console.error('[Cursor Sync] Failed to create state directory:', error);
                return;
            }
        }
        
        // 写入状态文件
        try {
            fs.writeFileSync(statePath, JSON.stringify(state, null, 2));
            lastUpdateTime = now; // 更新最后写入时间
            console.log(`[Cursor Sync] Updated state: ${statePath}`);
        } catch (error) {
            console.error('[Cursor Sync] Failed to write state file:', error);
        }
    } catch (error) {
        console.error('[Cursor Sync] Failed to update state:', error);
    }
}

// 打开指定文件位置
async function openFileAtPosition(filePath, lineNumber, column) {
    try {
        // 验证文件路径
        if (!filePath || !fs.existsSync(filePath)) {
            throw new Error('Invalid file path');
        }

        // 转换为绝对路径
        const absolutePath = path.resolve(filePath);
        
        // 打开文件
        const document = await vscode.workspace.openTextDocument(absolutePath);
        const editor = await vscode.window.showTextDocument(document);
        
        // 设置光标位置
        const position = new vscode.Position(
            Math.max(0, lineNumber - 1),  // 转换为0基索引
            Math.max(0, column - 1)       // 转换为0基索引
        );
        
        // 设置选择范围
        editor.selection = new vscode.Selection(position, position);
        
        // 确保光标位置可见
        editor.revealRange(
            new vscode.Range(position, position),
            vscode.TextEditorRevealType.InCenter
        );
        
        console.log(`[Cursor Sync] Opened file at position: ${absolutePath}:${lineNumber}:${column}`);
        return true;
    } catch (error) {
        console.error('[Cursor Sync] Failed to open file:', error);
        vscode.window.showErrorMessage(`无法打开文件: ${error.message}`);
        return false;
    }
}

// 读取参数文件并打开指定文件位置 快捷键没有生效
async function openFileFromArgsFile() {
    try {
        const homeDir = os.homedir();
        const argsPath = path.join(homeDir, '.eclipse-cursor-sync-plugin', 'eclipse_editor_state.json');
        if (!fs.existsSync(argsPath)) {
            vscode.window.showErrorMessage('参数文件不存在: ' + argsPath);
            return false;
        }
        let argsRaw = fs.readFileSync(argsPath, 'utf-8');
        let args;
        try {
            args = JSON.parse(argsRaw);
        } catch (e) {
            vscode.window.showErrorMessage('参数文件格式错误: ' + e.message);
            return false;
        }
        const { file_path, line_number, column } = args;
        if (!file_path || !line_number || !column) {
            vscode.window.showErrorMessage('参数缺失: file_path/line_number/column');
            return false;
        }
        return await openFileAtPosition(file_path, line_number, column);
    } catch (error) {
        vscode.window.showErrorMessage('读取参数文件失败: ' + error.message);
        return false;
    }
}

// 插件激活函数
function activate(context) {
    try {
        // 创建输出通道
        outputChannel = vscode.window.createOutputChannel('Cursor Sync');
        outputChannel.appendLine('插件已激活');
        
        // 验证插件目录
        const extensionPath = context.extensionPath;
        if (!extensionPath || !fs.existsSync(extensionPath)) {
            throw new Error('Invalid extension path');
        }
        
        // 注册同步命令
        let syncCommand = vscode.commands.registerCommand('cursor-sync-plugin.syncState', () => {
            updateStateFile();
            vscode.window.showInformationMessage('光标状态已同步');
        });

        // 注册打开文件命令（无参数，自动读取参数文件）
        let openFileCommand = vscode.commands.registerCommand('cursor-sync-plugin.openFile', async () => {
            try {
                outputChannel.appendLine('尝试打开文件...');
                const result = await openFileFromArgsFile();
                if (!result) {
                    const message = '打开文件失败，请检查参数文件是否存在且格式正确';
                    outputChannel.appendLine(message);
                    vscode.window.showErrorMessage(message);
                }
                return result;
            } catch (error) {
                const message = `打开文件时发生错误: ${error.message}`;
                outputChannel.appendLine(message);
                outputChannel.appendLine(error.stack);
                vscode.window.showErrorMessage(message);
                return false;
            }
        });
        
        // 初始更新
        updateStateFile();
        
        // 监听编辑器切换事件
        const editorChange = vscode.window.onDidChangeActiveTextEditor(editor => {
            if (editor) {
                outputChannel.appendLine('活动编辑器已更改');
                updateStateFile();
            }
        });
        
        // 监听光标位置变化
        const cursorMove = vscode.window.onDidChangeTextEditorSelection(event => {
            if (event.textEditor === vscode.window.activeTextEditor) {
                outputChannel.appendLine('光标位置已更改');
                updateStateFile();
            }
        });
        
        // 监听文件保存事件
        const saveDocument = vscode.workspace.onDidSaveTextDocument(document => {
            if (vscode.window.activeTextEditor && 
                vscode.window.activeTextEditor.document === document) {
                outputChannel.appendLine('文档已保存');
                updateStateFile();
            }
        });
        
        // 注册清理回调
        context.subscriptions.push(syncCommand, openFileCommand, editorChange, cursorMove, saveDocument);
        
        outputChannel.appendLine('插件初始化成功');
    } catch (error) {
        if (outputChannel) {
            outputChannel.appendLine('插件激活失败: ' + error.message);
            outputChannel.appendLine(error.stack);
        }
        throw error;
    }
}

// 插件停用函数
function deactivate() {
    try {
        if (outputChannel) {
            outputChannel.appendLine('插件已停用');
            outputChannel.dispose();
        }
    } catch (error) {
        console.error('[Cursor Sync] Error during deactivation:', error);
    }
}

module.exports = {
    activate,
    deactivate
};